package org.or5e.service.core.ds.fm;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.or5e.service.core.dao.UserLogin;
import org.or5e.service.core.ds.BasicDataSource;
import org.or5e.service.core.ds.DataSourceFactory;
import org.or5e.service.core.sm.SessionManager;

public class FriendMasterImpl extends BasicDataSource implements FriendMasterDataSource {

	public FriendMasterImpl(SessionFactory sessionFactory, SessionManager sessionManager) {
		super(sessionFactory, sessionManager);
	}

	@Override
	public List<org.or5e.service.core.dao.FriendMaster> getFriends(String userID) {
		debug("Trying to aquire the Friend list for :"+userID);
		Session session = sessionFactory.openSession();
		
		@SuppressWarnings("unchecked")
		List<org.or5e.service.core.dao.FriendMaster> friendList = (List<org.or5e.service.core.dao.FriendMaster>)session.createQuery("from FriendMaster e where e.userID='"+userID+"'").list();
		if(friendList != null && friendList.size() > 0) {
			return friendList;
		}
		return null;
	}

	@Override
	public List<org.or5e.service.core.dao.FriendMaster> getUserAndFriend(UserLogin userLogin) {
		return getFriends(String.valueOf(userLogin.getUserID()));
	}

	@Override
	public void addFriendToList(String userID, List<org.or5e.service.core.dao.FriendMaster> frndList) {
		Session session = sessionFactory.openSession();
		Transaction friendMasterTransaction = session.beginTransaction();
		friendMasterTransaction.begin();
		try {
			int count = 0;
			for (org.or5e.service.core.dao.FriendMaster friendMaster : frndList) {
				session.save(friendMaster);
				if(count++ % 19 > 0) {
					session.flush();
					session.clear();
				}
			}
		}
		catch(Exception e) {
			e.printStackTrace();
			friendMasterTransaction.rollback();
			session.close();
			return;
		}
		friendMasterTransaction.commit();
		session.flush();
		session.clear();
		session.close();
	}

	@Override
	public String getName() {
		return "FriendMasterImpl";
	}
	
	public static void main(String[] args) {
		org.or5e.service.core.ds.fm.FriendMasterDataSource fMaster = (org.or5e.service.core.ds.fm.FriendMasterDataSource)DataSourceFactory.getDataSourceFactory().getDataSource(FriendMasterDataSource.class);
		List<org.or5e.service.core.dao.FriendMaster> friends = fMaster.getFriends("1002");
		for (org.or5e.service.core.dao.FriendMaster friendMaster : friends) {
			System.out.println("Friend :"+friendMaster.getFriendUserID());
		}
		
		friends = fMaster.getFriends("1001");
		for (org.or5e.service.core.dao.FriendMaster friendMaster : friends) {
			System.out.println("Friend :"+friendMaster.getFriendUserID());
		}
		fMaster.closeDataSource();
	}
}